package com.solution.common.utils.importExcel;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

import jxl.Cell;
import jxl.CellType;
import jxl.DateCell;
import jxl.NumberCell;
import jxl.Workbook;
import jxl.read.biff.BiffException;

import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

/**
 * 
 * <ul>
 * <li>Title:Excel导入工具类</li>
 * <li>Description:</li>
 * <li>Copyright: www.gzzyzz.com</li>
 * <li>Company:</li>
 * </ul>
 * 
 * @author Hill
 * @version 2013-11-26
 */
public class ExcelUtil {

    /**
     * 传入行对象，及列索引，获取制定列测单元格值
     * 
     * @param row
     * @param colIndex
     * @return String
     * @author xu_cc
     * @throws Exception
     *             exception
     * @Date 创建时间：2017年9月27日 上午10:33:24
     */
    private static String getCellStringValue(Row row, int colIndex) {
        try {
            org.apache.poi.ss.usermodel.Cell cell = (null != row) ? row.getCell(colIndex) : null;
            cell.setCellType(org.apache.poi.ss.usermodel.Cell.CELL_TYPE_STRING);
            return (null != cell) ? cell.getStringCellValue() : null;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * MultipartFile 转换成File
     * 
     * @param multfile
     *            原文件类型
     * @return File
     * @throws IOException
     */
    public static File multipartToFile(MultipartFile multfile) throws IOException {
        CommonsMultipartFile cf = (CommonsMultipartFile) multfile;
        // 这个myfile是MultipartFile的
        DiskFileItem fi = (DiskFileItem) cf.getFileItem();
        File file = fi.getStoreLocation();
        // 手动创建临时文件
        File tmpFile = new File(System.getProperty("java.io.tmpdir") + System.getProperty("file.separator") + file.getName());
        multfile.transferTo(tmpFile);
        return tmpFile;
    }

    /**
     * 以POI的方式读取excel2007之后的版本，XLSX格式的文件
     * 
     * @param file
     * @param sheetIndex
     * @return List<Map<String,String>>
     * @author xu_cc
     * @throws Exception
     *             exception
     * @Date 创建时间：2017年9月27日 上午10:48:36
     */
    public static final List<Map<String, String>> readSheet2007(MultipartFile file, int sheetIndex) {
        try {
            org.apache.poi.ss.usermodel.Workbook workbook = new XSSFWorkbook(file.getInputStream());
            Sheet sheet = workbook.getSheetAt(sheetIndex);
            // 行数
            int rowSize = sheet.getLastRowNum() + 1;// 总行数（必须+1）
            // 获取第一行
            Row headRow = sheet.getRow(0);
            // 列数
            int colSize = headRow.getLastCellNum();
            // 读取标题
            String[] titleArr = new String[colSize];
            for (int i = 0; i < colSize; i++) {
                String title = getCellStringValue(headRow, i);
                if (null == title) {
                    throw new Exception("标题不可为空！请看第一行，第" + (i + 1) + "列");
                }
                titleArr[i] = title;
            }
            List<Map<String, String>> mapList = new ArrayList<Map<String, String>>();
            Map<String, String> map = null;
            row:
            // 逐行读取，从第二行开始
            for (int i = 1; i < rowSize; i++) {
                map = new HashMap<String, String>();
                Row dataRow = sheet.getRow(i);
                col: // 某一行逐列读取数据
                for (int j = 0; j < colSize; j++) {
                    String cellVal = getCellStringValue(dataRow, j);
                    map.put(titleArr[j], cellVal);
                }
                mapList.add(map);
            }
            return mapList;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 从excel文件中读取内容 以第一行为key，从第二行开始为正式数据<br>
     * 仅限于读取excel-2003 xls类型文件
     * 
     * @param file
     * @param sheetIndex
     * @return
     * @throws BiffException
     * @throws IOException
     */
    public static final List<Map<String, String>> readSheet(File file, int sheetIndex) {
        Workbook workbook = null;
        List<Map<String, String>> result = null;
        try {
            workbook = Workbook.getWorkbook(file);
            jxl.Sheet sheet = workbook.getSheet(0);
            int rowSize = sheet.getRows();
            Cell[] headCell = sheet.getRow(0);
            result = new ArrayList<Map<String, String>>(rowSize - 1);
            Cell[] cells;
            for (int i = 1; i < rowSize; i++) {
                cells = sheet.getRow(i);
                Map<String, String> data = new HashMap<String, String>();
                for (int j = 0; j < headCell.length; j++) {
                    if (cells.length > j) {
                        if (cells[j].getType() == CellType.DATE) { // TODO:时间类型读取
                            DateCell dc = (DateCell) cells[j];
                            Date date = dc.getDate();
                            TimeZone zone = TimeZone.getTimeZone("GMT");
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            sdf.setTimeZone(zone);
                            String dateStr = sdf.format(date);
                            data.put(trim(headCell[j].getContents()), dateStr);
                        } else if (cells[j].getType() == CellType.NUMBER) { // 数字类型读取
                            if (cells[j].getContents().indexOf(".") > 0) {
                                NumberCell nc = (NumberCell) cells[j];
                                double value = nc.getValue();
                                data.put(trim(headCell[j].getContents()), trim(String.valueOf(value)));
                            } else {
                                data.put(trim(headCell[j].getContents()), trim(cells[j].getContents()));
                            }
                        } else {
                            data.put(trim(headCell[j].getContents()), trim(cells[j].getContents()));
                        }

                    }
                }
                result.add(data);
            }
        } catch (BiffException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            workbook.close();
        }

        return result;
    }

    /**
     * 从excel文件中读取内容 以第一行为key，从第二行开始为正式数据
     * 
     * @param file
     * @param sheetIndex
     * @return
     * @throws BiffException
     * @throws IOException
     */
    // public static final List<Map<String, String>> file(InputStream
    // inputStream, int sheetIndex) {
    // Workbook workbook = null;
    // List<Map<String, String>> result = null;
    // try {
    // workbook = Workbook.getWorkbook(inputStream);
    // jxl.Sheet sheet = workbook.getSheet(0);
    // int rowSize = sheet.getRows();
    // Cell[] headCell = sheet.getRow(0);
    // result = new ArrayList<Map<String, String>>(rowSize - 1);
    // Cell[] cells;
    // for (int i = 1; i < rowSize; i++) {
    // cells = sheet.getRow(i);
    // Map<String, String> data = new HashMap<String, String>();
    // for (int j = 0; j < headCell.length; j++) {
    // if (cells.length > j) {
    // if (cells[j].getType() == CellType.DATE) { // TODO:时间类型读取
    // DateCell dc = (DateCell) cells[j];
    // Date date = dc.getDate();
    // TimeZone zone = TimeZone.getTimeZone("GMT");
    // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    // sdf.setTimeZone(zone);
    // String dateStr = sdf.format(date);
    // data.put(trim(headCell[j].getContents()), dateStr);
    // } else if (cells[j].getType() == CellType.NUMBER) { // 数字类型读取
    // if (cells[j].getContents().indexOf(".") > 0) {
    // NumberCell nc = (NumberCell) cells[j];
    // double value = nc.getValue();
    // data.put(trim(headCell[j].getContents()), trim(String.valueOf(value)));
    // } else {
    // data.put(trim(headCell[j].getContents()), trim(cells[j].getContents()));
    // }
    // } else {
    // data.put(trim(headCell[j].getContents()), trim(cells[j].getContents()));
    // }
    //
    // }
    // }
    // result.add(data);
    // }
    // } catch (BiffException e) {
    // e.printStackTrace();
    // } catch (IOException e) {
    // e.printStackTrace();
    // } catch (Exception e) {
    // e.printStackTrace();
    // } finally {
    // workbook.close();
    // }
    //
    // return result;
    // }

    private static final String trim(String str) {
        return str == null ? "" : str.trim();
    }
}
